package com.xxl.job.executor.core.config;

import org.beetl.sql.core.InterceptorContext;
import org.beetl.sql.ext.DebugInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * 自定义SQL日志拦截器
 * 
 * @author li
 *
 */
@Configuration
public class EnhancementSqlInterceptors extends DebugInterceptor {
	private static final Logger log = LoggerFactory.getLogger("EnhancementSql");
	@Autowired
	@Value("${beetlsql.show-SQL}")
	private boolean showSql;

	@Override
	public void before(InterceptorContext ctx) {
		if (showSql) {
			super.before(ctx);
		}
	}

	@Override
	public void after(InterceptorContext ctx) {
		if (showSql) {
			super.after(ctx);
		}
	}

	@Override
	public void exception(InterceptorContext ctx, Exception ex) {
		String sqlId = ctx.getSqlId();
		if (this.isSimple(sqlId)) {
			this.simpleOutException(ctx, ex);
			return;
		}
		String lineSeparator = System.getProperty("line.separator", "\n");
		StringBuilder sb = (StringBuilder) ctx.get("logs");
		sb.append("┗━━━━━ 错误信息").append(ex != null ? ex.getMessage().replace(lineSeparator, "") : "").append("] ━━━")
				.append(lineSeparator);
		log.error("SQL执行异常\n{}", sb.toString());
	}

	@Override
	protected void println(String str) {
		log.info("\n{}", str);
	}

}
